﻿/*
docs.taojen.com
www.pingtaimeng.com
*/
if (!$.browser) {//jquery 1.9已移除browser.
    // Useragent RegExp
    rwebkit = /(webkit)[ \/]([\w.]+)/;
    ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/;
    rmsie = /(msie) ([\w.]+)/;
    rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/;

    $.browser = {};
    $.uaMatch = function (ua) {
        ua = ua.toLowerCase();

        var match = rwebkit.exec(ua) ||
			ropera.exec(ua) ||
			rmsie.exec(ua) ||
			ua.indexOf("compatible") < 0 && rmozilla.exec(ua) ||
			[];

        return { browser: match[1] || "", version: match[2] || "0" };
    };

    //userAgent = navigator.userAgent,

    browserMatch = $.uaMatch(navigator.userAgent);
    if (browserMatch.browser) {
        $.browser[browserMatch.browser] = true;
        $.browser.version = browserMatch.version;
    }
}

//主框架代码开始
(function ($, undefined) {
    var common = (function () {
        var common = function (selector, context) {//调用$(selector)时,实际是调用这个函数.
            return new common.fn.init(selector, context);
        };
        //实例方法开始
        common.fn = {
            constructor: common,
            init: function (selector, context) {
                this.jo = $(selector, context);
                return this;
            }
        };
        common.prototype = common.fn;
        //实例方法结束
        common.fn.init.prototype = common.fn;
        //静态方法开始

        //静态成员结束
        return common; //这个common就是$c
    })();
    window.common =window.pingtaimeng=window.$g=window.$k=window.$c = common;
})(jQuery);
//主框架代码结束

//静态方法开始
$.extend($c, {
    file: {
        getFileFormat: function (path) {
            path = path.toLowerCase();
            return path.substr(path.lastIndexOf('.'));
        },
        isImg: function (path) {
            var format = common.file.getFileFormat(path);
            if (format == '.jpg' || format == '.jpeg' || format == '.bmp' || format == '.gif' || format == '.png') {
                return true;
            }
            return false;
        },
        isWord: function (path) {
            var format = common.file.getFileFormat(path);
            if (format == '.doc' || format == '.docx') {
                return true;
            }
            return false;
        },
        isPdf: function (path) {
            var format = common.file.getFileFormat(path);
            if (format == '.pdf') {
                return true;
            }
            return false;
        }
    },
    regex: {
        regexEnum: {
            //mobile: "^((13[0-9]{9})|(15[012356789][0-9]{8})|(18[012356789][0-9]{8})|(147[0-9]{8}))$", //手机
	    mobile: "^1[0-9]{10}$",	
            //tel: "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})$", //电话,例如:086-0851-1234567
            tel: "^((0\\d{2,3})-)?(\\d{7,8})$", //电话(可带区号可不带区号)
            tel_haveAreaCode: "^((0\\d{2,3})-)(\\d{7,8})$", //电话(必须带区号)
            tel_NoAreaCode: "^(\\d{7,8})$", //电话(不带区号)
            url: "^http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?$",
            areacode: "^0\\d{2,3}$"//区号
        },
        validator: {
            isMobile: function (mobile) {

                return new RegExp(common.regex.regexEnum.mobile, 'ig').test(mobile);
            },
            isTel: function (tel, haveAreacode) {
                var strRegex = common.regex.regexEnum.tel;
                if (haveAreacode == true) {
                    strRegex = common.regex.regexEnum.tel_haveAreaCode;
                }
                if (haveAreacode == false) {
                    strRegex = common.regex.regexEnum.tel_NoAreaCode;
                }
                return new RegExp(strRegex, 'ig').test(tel);
            },
            isUrl: function (url) {
                return new RegExp(common.regex.regexEnum.url, 'ig').test(url);
            },
            isAreaCode: function (areacode) {
                return new RegExp(common.regex.regexEnum.areacode, 'ig').test(areacode);
            }
        }
    },
    array: {
        select: function (arr, fun) {
            if (!$.isArray(arr) || !$.isFunction(fun)) {
                return undefined;
            }
            var _arr = [];
            $.each(arr, function (i, o) {
                _arr.push(fun(i, o));
            });
            return _arr;
        },
        first: function (arr, fun) {
            if (!$.isArray(arr) || !$.isFunction(fun)) {
                return undefined;
            }
            var obj = undefined;
            $.each(arr, function (i, o) {
                if (obj == undefined && fun(i, o) == true) {
                    obj = o;
                }
            });
            return obj;
        },
        where: function (arr, fun) {
            //            if (!$.isArray(arr) || !$.isFunction(fun)) {例如:$("input[type='checkbox']")不是数组.
            if (!$.isFunction(fun)) {
                return undefined;
            }
            var _arr = [];
            $.each(arr, function (i, o) {
                if (fun(i, o) == true) {
                    _arr.push(o);
                }
            });
            return _arr;
        },
        indexOf: function (arr, fun) {
            if (!$.isFunction(fun)) {
                return undefined;
            }
            var index = -1;
            $.each(arr, function (i, o) {
                if (index > -1) {
                    return;
                }
                if (fun(i, o) == true) {
                    index = i;
                }
            });
            return index;
        }
    },
    date: {
        isDateJson: function (_date) {//判断是否为日期的Json格式
            return /Date\((.+)\)/.test(_date);
        },
        toDateFromDateJson: function (dateJson) {
            return $.evalJSON({ date: dateJson }).date;
        },
        format: function (_date, fmt) {
            if (!_date) {
                return '';
            }
            if ($c.date.isDateJson(_date)) {
                _date = $c.date.toDateFromDateJson(_date);
            }
            var o = {
                "M+": _date.getMonth() + 1,                 //月份 
                "d+": _date.getDate(),                    //日 
                "h+": _date.getHours(),                   //小时 
                "m+": _date.getMinutes(),                 //分 
                "s+": _date.getSeconds(),                 //秒 
                "q+": Math.floor((_date.getMonth() + 3) / 3), //季度 
                "S": _date.getMilliseconds()             //毫秒 
            };
            if (/(y+)/.test(fmt))
                fmt = fmt.replace(RegExp.$1, (_date.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt))
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        }
    },
    //cookie start
    cookie: {//示例:$c.cookie.set("minprice", 50, '', 0, "/abc/");
        get: function (name) {
            var values = document.cookie.match(new RegExp(name + "=([^&;]+)"));
            if (values != null) {
                return decodeURI(values[1]);
            } return null;
        },
        setcookie: function (name, value) {
            $c.cookie.set(name, value, document.domain, null, '/');
        },
        set: function (name, value, domain, expireDays, path) {
            if (!domain) {
                domain = document.domain;
            }
            if (!path) {
                path = '/';
            }
            //var strCookie = name + "=" + escape(value) + ";";
            var strCookie = name + "=" + encodeURI(value) + ";";
            if (domain && domain != '') {
                strCookie = strCookie + "domain=" + domain + ";";
            }
            if (expireDays && expireDays > 0) {
                var exp = new Date();
                exp.setTime(exp.getTime() + (86400 * 1000 * expireDays));
                strCookie = strCookie + "expires=" + exp.toGMTString() + ";";
            }
            else {
                var exp = new Date();
                exp.setTime(exp.getTime() + (86400 * 1000 * 365));
                strCookie = strCookie + "expires=" + exp.toGMTString() + ";";
            }
            if (path && path != '') {
                strCookie = strCookie + "path=" + path + ";";
            }
            document.cookie = strCookie;
        },
        del: function (name, domain, path) {
            //$c.cookie.set(name, ' ', '', -1, '/');
            if (!domain) {
                domain = document.domain;
            }
            if (!path) {
                path = '/';
            }
            $c.cookie.set(name, ' ', domain, -1, path);
        }
    }, //cookie end
    getJSON: function (url, data, success) {
        return jQuery.get(url, data, function (response, status, xhr) {
            if (status == 'success'){
                success(eval('(' + response + ')'),status,xhr);
            }
        });
    },
    downloadFile: function (fileUrl, fileName) {
        if (!fileName) {
            fileName = '';
        }
        var rnd = parseInt(Math.random() * 10000000, 10);
        var formHtml = '<div style="display: none;">';
        formHtml += '<form id="form_' + rnd + '" name="form_' + rnd + '" method="post" enctype="multipart/form-data" action="/file/download" target="fr_' + rnd + '">';
        formHtml += '';
        formHtml += '<input type="hidden" name="url" value="' + fileUrl + '" />';
        formHtml += '<input type="hidden" name="fileName" value="' + fileName + '" />';
        formHtml += '</form>';
        formHtml += '<iframe name="fr_' + rnd + '"></iframe>';
        formHtml += '</div>';
        $('body').append(formHtml);
        var f = document.getElementById("form_" + rnd + "");
        f.submit();
    }
});
$g.zIndex = 10000;//全局变量
//静态方法结束

//实例方法开始
//实例方法结束

$.fn.setStyle = function (style) {
    var _this = $(this);
    if (_this.length == 0) {
        return;
    }
    if (!style || ('object' != typeof style)) {
        return;
    }
    $.each(style, function (k, v) {
        k = k.replace(/_/g, "-");//js变量名不能有'-',css中样式名都是'-'.注意:k.replace('_', '-')只会替换第一个'_'.
        v = $.trim(v);
        if (v == '') {
            return;
        }
        _this.css(k, v);
    });
};


//表单系列化为对象,如:$('#form1').serializeForm()
$.fn.serializeForm = function () {
    var arr = $(this).serializeArray();
    var obj = {};
    $.each(arr, function (i, o) {
        obj[o.name] = o.value;
    });
    return obj;
}

//Jquery静态方法扩展.
$.evalJSON = function (strJson) {
    function _f1(_s) {
        for (n in _s) {
            if (_s[n] && typeof (_s[n]) == "object")
                _f1(_s[n]);

            if (/Date\((.+)\)/.test(_s[n]))
                _s[n] = (new Date(parseInt(RegExp.$1)));
        }
        return _s;
    }
    return _f1(strJson);
}

$.extendEx = function () {
    //a和b同时具有的简单属性,用b中的属性替换a,对于object属性继续深度遍历比较简单属性.
    //例如:$.extendEx({type:1,style:{width:50,height:100}},{type:2,style:{width:300,bgColor:'#f00'}}); 结果为:{type:2,style:{width:300,height:100,bgColor:'#f00'}}
    var travel = function () {
        //对象不能直接赋值,否则不是深克隆.
        $.each(_objB, function (k, v) {
            //if (('object' == typeof v) && !$.isArray(v)) {
            if (('object' == typeof v) && !(v instanceof jQuery)) {
                //if (!_objA[k] || ('object' != typeof _objA[k]) || $.isArray(_objA[k])) {//v对对象,_objA[k]没有定义或者定义了但不是一个对象.
                if (v == null || v == undefined) {
                    _objA[k] = v;
                }
                    //else if (!_objA[k] || ('object' != typeof _objA[k]) || (($.isArray(_objA[k]) && !$.isArray(v)) || (!$.isArray(_objA[k]) && $.isArray(v)))) { //数组也是object,对数据中的每一项也可以进行继承操作
                    //    _objA[k] = v;//直接替换：1、_objA[k]没有定义.2、_objA[k]是简单类型数据.3、_objA[k]是数组_objB[k]不是数组.4、_objA[k]不是数组_objB[k]是数组.
                    //}
                else {
                    var _a = _objA;
                    var _b = _objB;

                    if ($.isArray(v)) {//v是数组.
                        if (!$.isArray(_objA[k])) {
                            _objA[k] = [];
                        }
                    }
                    else {//v是{}类型
                        if (('object' != typeof _objA[k]) || $.isArray(_objA[k])) {
                            _objA[k] = {};
                        }
                    }

                    _objA = _objA[k];
                    _objB = v;

                    travel();//递归调用.
                    //跳出递归,把_objA、和_objB还原为递归之前的.
                    _objA = _a;
                    _objB = _b;
                }
            }
            else {
                _objA[k] = v;
            }
        });
    };
    if (arguments.length < 2) {
        return;
    }
    var _objA = null;
    var _objB = null;
    for (var i = 0; i < arguments.length - 1; i++) {
        _objA = arguments[0];
        _objB = arguments[i + 1];
        if (_objB&&('object' == typeof _objB) && !$.isArray(_objB)) {
            travel();
        }
    }
    return arguments[0];
};

var Guid = {
    NewGuid: function () {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth()+1;
        if (month < 10) {
            month = '0' + month;
        }
        var day = date.getDate();
        if (day < 10) {
            day = '0' + day;
        }
        var hour = date.getHours();
        if (hour < 10) {
            hour = '0' + hour;
        }
        var minutes = date.getMinutes();
        if (minutes < 10) {
            minutes = '0' + minutes;
        }
        var seconds = date.getSeconds();
        if (seconds < 10) {
            seconds = '0' + seconds;
        }
        var milliSeconds = date.getMilliseconds();
        if (milliSeconds < 10) {
            milliSeconds = '00' + milliSeconds;
        }
        else if (milliSeconds < 100) {
            milliSeconds = '0' + milliSeconds;
        }
        var rnd = Math.floor(Math.random() * 1000000000000);
        var guid = 'guid' + year + month + hour + minutes + seconds + milliSeconds + rnd;
        return guid;
    }
};